package org.sczfdf.utils;

import cn.hutool.core.util.StrUtil;
import org.sczfdf.conf.LogConf;
import org.sczfdf.formatter.SyncFormatter;

import java.util.Map;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Created by cgb
 * @date 2023/1/31
 */
public class LogUtil {
    private static volatile boolean initFinal = false;

    private static final Logger log = Logger.getGlobal();

    static {
        try {
            ConsoleHandler handler = new ConsoleHandler();
            handler.setLevel(Level.INFO);
            handler.setFormatter(new SyncFormatter());
            log.addHandler(handler);

            log.setUseParentHandlers(false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        LogConf logConf = LogConf.get();
        if (StrUtil.isBlankIfStr(logConf.getLogFile())) {
            // 空就不写文件
            initFinal = true;
        }

        if (!logConf.isLogFileLazy()) {
            // 非懒加载日志文件就直接写日志
            init();
        }

    }

    private static void init() {
        try {
            LogConf logConf = LogConf.get();

            FileHandler handler = new FileHandler(logConf.getLogFile());
            handler.setLevel(Level.parse(logConf.getLogFileLevel()));
            handler.setFormatter(new SyncFormatter());
            log.addHandler(handler);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            initFinal = true;
        }
    }

    public static void logError(String msg) {
        if (!initFinal) {
            init();
        }
        log.warning(msg);
    }

    public static void logInfo(Map<String, Object> map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            log.info(entry.getKey() + "=" + entry.getValue());
        }
    }
    public static void logInfo(String msg) {
        log.info(msg);
    }
}
